//
//  CreateClubViewController.swift
//  MT
//
//  Created by ooops on 2020/1/12.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Eureka
import MTCategory
import YPNavigationBarTransition
import Kingfisher

extension MTCreateClubViewController: MTClubImageSelectCellDelegate {
    func clubAvatorDidChanged() {
        self.avatorUrl = nil
    }
}

class MTCreateClubViewController: BaseFormViewController {
    
    let provider: MTProvider = MTProvider<MTClubApi>()
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    /// 上传
    private lazy var upload_provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    
    private lazy var clubProvider: MTProvider<MTClubApi> = {
        let provider = MTProvider<MTClubApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()

    private var avatorUrl: String?
    
    private var redpacketDictionary: [String : String]?
    
    public typealias createClubCompleteCloseure = (Bool) -> Swift.Void
    
    private var completeCloseure: createClubCompleteCloseure?
    
    private var currentTextField: UITextField?
    /// 是否编辑模式
    private var isEditMode: Bool = false
    /// 俱乐部ID
    private var clubId: String?
    public var group: JMSGGroup!
    public var conversation: JMSGConversation!
    convenience init(complete: createClubCompleteCloseure?) {
        self.init()
        self.completeCloseure = complete
    }
    
    convenience init(isEditMode: Bool, clubId: String, complete: createClubCompleteCloseure?) {
        self.init()
        self.completeCloseure = complete
        self.isEditMode = isEditMode
        self.clubId = clubId
    }
    
    override func refreshView() {
        queryClubInfo()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "俱乐部创建信息"
        tableView.backgroundColor = UIColor(hex: 0xF4F4F4)
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: navBackButton)
        setupForm(isEditMode: isEditMode)
        view.addSubview(createClubButton)
        
        createClubButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
        
        if isEditMode {
            queryClubInfo()
            self.createClubButton.setTitle("完成编辑", for: .normal)
            self.title = "编辑俱乐部信息"
        }
        tableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
    }
    
    private func queryClubInfo() {
        guard let id = clubId else { return }
        MTClubTool.queryClubInfo(provider: clubProvider, requestParam: ["pushId": id], complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if model?.code == 200 {
                if let avator = model?.result?.href {
                    weakSelf.avatorUrl = avator
                    weakSelf.setValue(value: avator, forTag: clubAvatorKey)
                }
                
                if let name = model?.result?.name {
                    weakSelf.setValue(value: name, forTag: clubNameKey)
                }
                
                if let desc = model?.result?.remark {
                    weakSelf.setValue(value: desc, forTag: clubDescriptionKey)
                }
                
                if let p = model?.result?.province, let c = model?.result?.city, let a = model?.result?.area {
                    weakSelf.setValue(value: p + "-" + c + "-" + a, forTag: clubAddrKey)
                }
                
                if let rcount = model?.result?.redPacketNum, let rmoney = model?.result?.redPacketMoney, let rs = model?.result?.redPacketSendTime {
                    let requestParam: [String : String] = [clubRAmountKey: "\(rmoney)", clubRCountKey: "\(rcount)", clubDateKey: "\(rs)",]
                    if let row: MTRedpacketCellRow = weakSelf.form.rowBy(tag: clubGiftKey) as? MTRedpacketCellRow {
                        row.value = requestParam
                        row.reload()
                        row.cellUpdate { (cell, row) in
                            cell.height = { return 64 }
                        }
                    }
                }
            } else if model?.code == 500 {
                if let msg = model?.message {
                    MBProgressHUD_JChat.show(text: msg, view: weakSelf.view, 1)
                }
            }
            
        }) { (error) in
            
        }
    }
    
    /// 赋值
    /// - Parameters:
    ///   - value:
    ///   - tag:
    private func setValue(value: String, forTag tag: String) {
        switch tag {
        case clubAvatorKey:
            if let row: MTClubImageSelectRow = self.form.rowBy(tag: tag) as? MTClubImageSelectRow {
                //row.reload()
                row.avatorImageVIew.mtSetImage(value, nil)
            }
        case clubNameKey:
            if let row: MTNewClubNameCellRow = self.form.rowBy(tag: tag) as? MTNewClubNameCellRow {
                row.value = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    cell.height = { return 64 }
                }
            }
        case clubDescriptionKey:
            if let row: MTNewClubRemarkCellRow = self.form.rowBy(tag: tag) as? MTNewClubRemarkCellRow {
                row.value = value
                row.reload()
                row.cellUpdate { (cell, row) in

                    //cell.height = { return 64 }
                }
            }
        case clubAddrKey:
            if let row: MTNewClubEditAreaRow = self.form.rowBy(tag: tag) as? MTNewClubEditAreaRow {
                row.value = value
                row.reload()
                row.cellUpdate { (cell, row) in

                    cell.height = { return 64 }
                }
            }
        default:
            break
        }
    }
    
    @objc private func back() {
        if self.form.validate().count > 0 {
            self.pop()
            return
        }
            
        UIAlertController.rx.show(in: self, title: "提示", message: "如果退出，内容将丢失确定要继续退出？", buttons: [.cancel("取消"), .default("确定")]).subscribe(onSuccess: { [weak self] index in
            guard let weakSelf = self else { return }
            if index == 1 {
                weakSelf.pop()
            }
        })
        .disposed(by: globalDisposedBag)
    }
    
    private func showValidationMsg(msgs: [ValidationError]) {
        MBProgressHUD_JChat.show(text: msgs.first!.msg, view: self.view)
    }
    
    @objc private func uploadAvator() {
        
        let validationErrors: [ValidationError] = self.form.validate()
        if validationErrors.count != 0 {
            self.showValidationMsg(msgs: validationErrors)
            return
        }
        
        let values = self.form.values()
        
        if (values[clubAvatorKey] as? UIImage) == nil {
            MBProgressHUD_JChat.show(text: "请选择俱乐部头像", view: self.view)
            return
        }
        
        if let name = values[clubNameKey] as? String, (name.length > 10 || name.length == 0) {
            MBProgressHUD_JChat.show(text: "请输入10个字以内的俱乐部名称", view: self.view)
            return
        }
        
        if values[clubGiftKey] as? [String : String] == nil {
            MBProgressHUD_JChat.show(text: "请先设置俱乐部红包", view: self.view)
            return
        }
        
        if let giftDict = values[clubGiftKey] as? [String : String] {
            guard let _ = giftDict[clubRAmountKey] else {
                MBProgressHUD_JChat.show(text: "请设置总金额", view: self.view)
                return
            }
            
            guard let _ = giftDict[clubRCountKey] else {
                MBProgressHUD_JChat.show(text: "请设置红包个数", view: self.view)
                return
            }
            
            guard let _ = giftDict[clubDateKey] else {
                MBProgressHUD_JChat.show(text: "请设置发送时间", view: self.view)
                return
            }
        }
        
        if avatorUrl == nil {
            /// 拿图片
            let image: UIImage = values[clubAvatorKey] as! UIImage
            MBProgressHUD_JChat.showProgress(self.view, text: "正在上传俱乐部头像")
            upload_provider.originRequest(.upload(image), callbackQueue: .global(), progress: { [weak self] (progressResonpse) in
                guard let weakself = self else { return }
                DispatchQueue.main.async {
                    debugPrint(Float(progressResonpse.progress * 100))
                    MBProgressHUD_JChat.modifyProgressHUD(weakself.view, progress: Float(progressResonpse.progress), text: "正在上传俱乐部头像")
                }
            }) { [weak self] (result, _) in
                guard let weakSelf = self else { return }
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                        if code == 200, let url = datas["result"] as? String {
                            DispatchQueue.main.async {
                                weakSelf.avatorUrl = url
                                weakSelf.createClubAction()
                                MBProgressHUD_JChat.dismiss(weakSelf.view)
                            }
                        } else {
                            DispatchQueue.main.async {
                                MBProgressHUD_JChat.dismiss(weakSelf.view)
                                MBProgressHUD_JChat.show(text: "图片上传失败", view: weakSelf.view)
                            }
                        }
                    }
                    break

                case .failure(_):
                    MBProgressHUD_JChat.dismiss(weakSelf.view)
                    MBProgressHUD_JChat.show(text: "图片上传失败", view: weakSelf.view)
                    break
                }
            }
        } else {
            createClubAction()
        }
        
    }
    
    // MARK: - 创建俱乐部
    @objc private func createClubAction() {
        
        let values = self.form.values()
        
        var requestParam: [String : Any] = ["id" : "", "area": "", "city": "", "province": "", "remark": "", "name": "", "href" : "", "redPacketMoney" : "", "redPacketNum" : "", "redPacketSendTime" : ""]
        
        if let squ: String = values[clubAddrKey] as? String {
            let array: [Substring] = squ.split(separator: "-")
            requestParam.updateValue(array[2], forKey: "area")
            requestParam.updateValue(array[1], forKey: "city")
            requestParam.updateValue(array[0], forKey: "province")
        }
        
        if let remark = values[clubDescriptionKey] as? String {
            requestParam.updateValue(remark, forKey: "remark")
        }
        
        if let name = values[clubNameKey] as? String {
            requestParam.updateValue(name, forKey: "name")
        }
        if let url = self.avatorUrl {
            requestParam.updateValue(url, forKey: "href")
        }
        
        if let redpacket = values[clubGiftKey] as? [String : Any] {
            if let redPacketMoney = redpacket[clubRAmountKey] as? String {
                requestParam.updateValue(redPacketMoney, forKey: "redPacketMoney")
            }
            if let redPacketNum = redpacket[clubRCountKey] as? String {
                requestParam.updateValue(redPacketNum, forKey: "redPacketNum")
            }
            if let redPacketSendTime = redpacket[clubDateKey] as? String {
                requestParam.updateValue(redPacketSendTime, forKey: "redPacketSendTime")
            }
        }
        /// 修改俱乐部信息
        if isEditMode {
            if let m = values["redPacketMoney"] as? String ,m == "" {
                MBProgressHUD_JChat.show(text: "请先设置俱乐部红包", view: self.view)
                return
            }
            
            if let num = values["redPacketNum"] as? String, num == "" {
                MBProgressHUD_JChat.show(text: "请先设置俱乐部红包", view: self.view)
                return
            }
            
            if let t = values["redPacketSendTime"] as? String, t == "" {
                MBProgressHUD_JChat.show(text: "请先设置俱乐部红包", view: self.view)
                return
            }
            
            requestParam.updateValue(clubId!, forKey: "pushId")
            MBProgressHUD_JChat.showLoading(self.view)
            MTClubTool.editClub(provider: self.provider, requestParam: requestParam, complete: { [weak self] (model) in
                guard let weakSelf = self else { return }
                MBProgressHUD_JChat.dismiss(weakSelf.view)
                if let m = model {
                    if m.code == 200 {
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "修改俱乐部信息成功", view: weakSelf.view)
                            DispatchQueue.main.after(1) {
                                weakSelf.completeCloseure?(true)
                                weakSelf.pop()
                            }
                        }
                    } else {
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "修改俱乐部信息失败", view: weakSelf.view)
                        }
                    }
                }
            }) { (error) in
                MBProgressHUD_JChat.dismiss(self.view)
                #if DEBUG
                MBProgressHUD_JChat.show(text: error.description, view: self.view)
                #endif
            }
        } else {
            MBProgressHUD_JChat.showLoading(self.view)
            MTClubTool.createClub(provider: self.provider, requestParam: requestParam, complete: { [weak self] (model) in
                guard let weakSelf = self else { return }
                MBProgressHUD_JChat.dismiss(weakSelf.view)
                if let m = model {
                    if m.code == 200, let pushId = m.clubInfo?.pushId {
                        JMSGConversation.createGroupConversation(withGroupId: "\(pushId)") { (result, error) in
                            if error == nil {
                                debugPrint("--------------------------- 创建俱乐部聊天成功")
                            }
                        }
                        DispatchQueue.main.async {
                            weakSelf.avatorUrl = nil
                            weakSelf.completeCloseure?(true)
                            weakSelf.pop()
                        }
                    } else if m.code == 520 { /// 创建俱乐部过于频繁
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: m.message ?? "", view: weakSelf.view)
                        }
                    } else {
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "创建俱乐部失败", view: weakSelf.view)
                        }
                    }
                }
            }) { (error) in
                MBProgressHUD_JChat.dismiss(self.view)
                #if DEBUG
                MBProgressHUD_JChat.show(text: error.description, view: self.view)
                #endif
            }
        }
    }
    
    // MARK: - 检查数据有效性
    private func validatorDataDictionary() {
        
        let validationErrors: [ValidationError] = self.form.validate()
        if validationErrors.count != 0 {
            createClubButton.isUserInteractionEnabled = false
            createClubButton.backgroundColor = UIColor.redpack.x5d5d5d
            return
        } else {
            createClubButton.isUserInteractionEnabled = true
            createClubButton.backgroundColor = UIColor.theme.main
        }
    }

    private func setupForm(isEditMode: Bool) {
        let section = Section()
        form +++ section
            <<< MTClubImageSelectRow(){ row in
                row.title = "请上传俱乐部头像（必填）"
                row.tag = clubAvatorKey
                row.delegate = self
            }
        let sectionTwo = Section()
        form +++ sectionTwo
            <<< MTNewClubNameCellRow(){ row in
                row.cell.tipString = isEditMode ? "俱乐部名称" : "名称（必填）"
                row.cell.contentString = " "
                row.cell.placeholder = "请输入俱乐部名称"
                row.cell.isEditMode = true
                //row.add(rule: MTClubNameRule())
                row.cell.height = { return 64 }
                row.tag = clubNameKey
                //row.updateCell()
            }.onChange({ (row) in
                //self.validatorDataDictionary()
            })
            
            <<< MTNewClubEditAreaRow() { row in
                row.cell.tipString = "地区"
                row.cell.contentString = " "
                row.cell.placeholder = "请选择您的城市"
                row.cell.isHiddenAccessory = false
                row.cell.isEditMode = true
                //row.add(rule: MTClubExCityNotNullRule())
                row.cell.height = { return 64 }
                row.tag = clubAddrKey
                //row.updateCell()
            }.onChange({ (row) in
                //self.validatorDataDictionary()
            })
        
        if isEditMode {
            let sectionhree = Section()
            form +++ sectionhree
                <<< MTNewClubDetailSwitchCellRow() { row in
                    row.cell.tipString = "置顶"
                    row.tag = "upflow"
                    row.cell.height = { return 64 }
                    row.value = self.conversation.ex.isSticky
                    //row.updateCell()
                }.onChange({ (row) in
                    self.conversation.ex.isSticky = !self.conversation.ex.isSticky
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
                })
                <<< MTNewClubDetailSwitchCellRow() { row in
                    row.cell.tipString = "消息免打扰"
                    row.cell.height = { return 64 }
                    row.tag = "Disturb"
                    row.value = self.group.isNoDisturb
                    //row.updateCell()
                }.onChange({ (row) in
                    if let dis = row.value {
                        self.group.setIsNoDisturb(dis, handler: { (result, error) in
                            MBProgressHUD_JChat.hide(forView: self.view, animated: true)
                            if error != nil {
                                row.value = !dis
                                MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view)
                            }
                        })
                    }
                })
        }
        let sectionFour = Section()
        form +++ sectionFour
            <<< MTRedpacketCellRow(){
                $0.title = "俱乐部红包"
                $0.value = self.redpacketDictionary
                $0.tag = clubGiftKey
                $0.cell.height = { return 64 }
                $0.cell.accessoryType = .none
            }.onChange({ (row) in
                self.redpacketDictionary = row.value
            })
            
            <<< MTNewClubRemarkCellRow(){ row in
                row.cell.tipString = "俱乐部简介"
                row.cell.contentString = " "
                row.cell.placeholder = "快来给大家介绍下你的俱乐部特色吧"
                row.cell.contentType = .editTextMutiply
                row.cell.isEditMode = true
                row.tag = clubDescriptionKey
                row.cell.maxTextLength = 50
                //row.add(rule: MTClubExDetailNotNullRule())
                //row.updateCell()
            }.onChange({ (row) in
                //self.validatorDataDictionary()
            })
        
        GroupTableSeparatorFix.removeFirstAndLastSeparatorLine()
    }
    
    lazy var createClubButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("完成创建", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.backgroundColor = UIColor.theme.main
        //btn.isUserInteractionEnabled = false
        btn.layer.cornerRadius = 22
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(uploadAvator), for: .touchUpInside)
        return btn
    }()
    
    lazy var navBackButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "nav_back"), for: .normal)
        btn.addTarget(self, action: #selector(back), for: .touchUpInside)
        return btn
    }()

}

extension MTCreateClubViewController {
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 11
    }
    
}

extension MTCreateClubViewController {

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
